Explain the Python Datetime with Example.
Explain the Python Datetime with Example.
756
07-Oct-2025
Updated on 23-Oct-2025
Mayank kumar Verma
23-Oct-2025Definition:
datetimemodule in Python is used to work with dates and times — like getting current date, formatting, or calculating time differences.from datetime import datetime
now = datetime.now()
print("Current Date and Time:", now)
Current Date and Time: 2025-10-23 14:35:22
ICSM Computer
08-Oct-20251. What is
datetimein Python?To use it:
2. Creating Date and Time Objects
You can create specific date/time objects using
datetime.date,datetime.time, ordatetime.datetime.Date object
Output:
Datetime object
Output:
3. Getting Components (Year, Month, etc.)
You can extract parts of the date/time:
Output:
4. Date Arithmetic (Add / Subtract Time)
You can add or subtract time using
timedelta.Output:
5. Formatting Dates and Times
Use
.strftime()to format datetime into strings.Output:
6. Parsing String to Datetime
Use
datetime.strptime()to convert string → datetime.Output:
7. Getting UTC Time and Timezones
Python’s
datetimecan handle UTC and time zones usingtimezone.Output:
8. Comparing Dates
You can directly compare two
datetimeordateobjects:Output:
9. Example — Days Until an Event
Output:
10. Example — Get Current Time in 12-Hour Format
Output:
Summary
datetime.now()datetime.today()timedelta(days=1)strftime()strptime()timezone.utc